<template>
  <div class="slide-list-container">
    <div class="page-header">
      <h2>轮播图管理</h2>
      <el-button type="primary" @click="openAddDialog">新增轮播图</el-button>
    </div>

    <!-- 轮播图列表 -->
    <el-table :data="slideList.records" style="width: 100%" v-loading="loading">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="商品名称" width="180">
          <template #default="scope">
            {{ getGoodName(scope.row.goodId) }}
          </template>
        </el-table-column>
        <el-table-column label="商品图片" width="150">
          <template #default="scope">
            <el-image
              v-if="getGoodImage(scope.row.goodId)"
              :src="getGoodImage(scope.row.goodId)"
              :preview-src-list="[getGoodImage(scope.row.goodId)]"
              style="width: 80px; height: 40px; cursor: pointer;"
              fit="cover"
              @click="handleImagePreview(getGoodImage(scope.row.goodId))"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
      <el-table-column prop="showOrder" label="显示顺序" width="100" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="slideList.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑轮播图对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="slideFormRef"
        :model="slideForm"
        label-width="100px"
        style="max-width: 500px;"
      >
        <el-form-item label="商品" prop="goodId" :rules="[{ required: true, message: '请选择商品', trigger: 'blur' }]">
        <el-select v-model="slideForm.goodId" placeholder="请选择商品" clearable filterable>
          <el-option
            v-for="good in goodsList"
            :key="good.id"
            :label="good.name"
            :value="good.id"
          />
        </el-select>
      </el-form-item>

      <!-- 商品预览 -->
      <el-form-item v-if="slideForm.goodId">
        <template #label>
          <span style="color: #606266;">商品预览</span>
        </template>
        <div class="preview-container">
          <img 
            v-if="getGoodImage(slideForm.goodId)" 
            :src="getGoodImage(slideForm.goodId)" 
            class="preview-image"
          />
          <div class="preview-info">
            <p>{{ getGoodName(slideForm.goodId) }}</p>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="显示顺序" prop="showOrder" :rules="[{ required: true, message: '请输入显示顺序', trigger: 'blur' }]">
        <el-input-number v-model="slideForm.showOrder" :min="1" :max="99" placeholder="请输入显示顺序" />
      </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="图片预览"
      width="90%"
      center
    >
      <img 
        :src="previewImageUrl" 
        alt="预览图片" 
        style="max-width: 100%; max-height: 80vh; object-fit: contain;"
      />
    </el-dialog>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Upload } from '@element-plus/icons-vue';
import axios from '../../lib/http';
import type { Carousel } from '../../api/carousel';
import { getCarousels, createCarousel, updateCarousel, deleteCarousels } from '../../api/carousel';

// 定义轮播图类型
interface Slide {
  id: number;
  goodId: number;
  showOrder: number;
  title?: string;
  imageUrl?: string;
}

// 商品信息接口
interface Good {
  id: number;
  name: string;
  imgs: string;
}

// 表格数据
const slideList = ref({ records: [] as Slide[], total: 0 });
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
// 商品列表
const goodsList = ref<Good[]>([]);

// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref('新增轮播图');
const slideFormRef = ref();
const slideForm = reactive({
  id: null,
  goodId: 0,
  showOrder: 0
});

// 图片预览
const previewVisible = ref(false);
const previewImageUrl = ref('');

// 加载商品列表
const loadGoodsList = async () => {
  try {
    const res = await axios.get('/api/good');
    if (res.data.code === 200 && res.data.data) {
      goodsList.value = res.data.data;
    }
  } catch (error) {
    console.error('加载商品列表失败:', error);
  }
};

// 获取商品名称
const getGoodName = (goodId: number) => {
  const good = goodsList.value.find(g => g.id === goodId);
  return good?.name || '未知商品';
};

// 获取商品图片
const getGoodImage = (goodId: number) => {
  const good = goodsList.value.find(g => g.id === goodId);
  if (good && good.imgs) {
    try {
      const imgs = JSON.parse(good.imgs);
      return imgs && imgs.length > 0 ? imgs[0] : 'https://via.placeholder.com/200x200?text=No+Image';
    } catch (e) {
      return good.imgs || 'https://via.placeholder.com/200x200?text=No+Image';
    }
  }
  return 'https://via.placeholder.com/200x200?text=No+Image';
};

// 加载轮播图列表
const loadSlideList = async () => {
  loading.value = true;
  try {
    const res = await getCarousels({
      current: currentPage.value,
      pageSize: pageSize.value
    });
    
    if (res.code === 200 && res.data) {
      slideList.value = {
        records: res.data.records || res.data,
        total: res.data.total || (res.data.records ? res.data.records.length : 0)
      };
    }
  } catch (error) {
    ElMessage.error('加载轮播图列表失败');
    console.error('加载轮播图列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  loadSlideList();
};

// 当前页变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  loadSlideList();
};

// 打开新增对话框
const openAddDialog = () => {
  dialogTitle.value = '新增轮播图';
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = (row: Slide) => {
  dialogTitle.value = '编辑轮播图';
  Object.assign(slideForm, row);
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  slideForm.id = null;
  slideForm.goodId = 0;
  slideForm.showOrder = 0;
  if (slideFormRef.value) {
    slideFormRef.value.resetFields();
  }
};

// 处理图片预览
const handleImagePreview = (imageUrl: string) => {
  previewImageUrl.value = imageUrl;
  previewVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  if (!slideFormRef.value) return;
  
  try {
    await slideFormRef.value.validate();
    
    // 创建一个副本，避免修改原始数据
    const formData = { ...slideForm };
    
    if (formData.id) {
      // 编辑模式
      const res = await updateCarousel(formData);
      if (res.code === 200) {
        ElMessage.success('轮播图更新成功');
        dialogVisible.value = false;
      } else {
        ElMessage.error(res.message || '轮播图更新失败');
      }
    } else {
      // 新增模式
      const res = await createCarousel(formData);
      if (res.code === 200) {
        ElMessage.success('轮播图创建成功');
        dialogVisible.value = false;
      } else {
        ElMessage.error(res.message || '轮播图创建失败');
      }
    }
    
    // 刷新列表
    loadSlideList();
  } catch (error) {
    ElMessage.error('操作失败，请重试');
    console.error('轮播图操作失败:', error);
  }
};

// 删除轮播图
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个轮播图吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const res = await deleteCarousels([id]);
    if (res.code === 200) {
      ElMessage.success('轮播图删除成功');
      // 刷新轮播图列表
      loadSlideList();
    } else {
      ElMessage.error(res.message || '轮播图删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除轮播图失败');
      console.error('删除轮播图失败:', error);
    } else {
      ElMessage.info('已取消删除');
    }
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadGoodsList();
  loadSlideList();
});
</script>

<style scoped>
.slide-list-container {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>